package io_driver

import (
	"clean/usecase/io/pb"
	"fmt"
)

type Handler func(in pb.Input, out *pb.Output)

type CommonRouter struct {
	routes         map[string]Handler
	defaultHandler Handler
}

func (r *CommonRouter) Get(name string) Handler {
	if r.routes == nil {
		return nil
	}
	if h, ok := r.routes[name]; ok {
		return h
	} else {
		return r.defaultHandler
	}
}

func (r *CommonRouter) SetDefaultHandler(h Handler) {
	r.defaultHandler = h
}

func (r *CommonRouter) Register(name string, handler Handler) {
	if r.routes == nil {
		r.routes = map[string]Handler{}
	}
	if _, ok := r.routes[name]; ok {
		panic(fmt.Sprintf("注册名称%v重复", name))
	}
	r.routes[name] = handler
}
